package com.demo.youxuanmall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.youxuanmall.common.Result;
import com.demo.youxuanmall.entity.User;
import com.demo.youxuanmall.mapper.UserMapper;
import com.demo.youxuanmall.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final PasswordEncoder passwordEncoder;
    private final UserMapper userMapper;

    @Override
    @Transactional
    public User register(User user) {
        // 检查用户名是否存在
        if (getByUsername(user.getUsername()) != null) {
            throw new RuntimeException("用户名已存在");
        }

        // 检查是否是管理员注册
        if (user.getRole() != null && user.getRole() == 1) {
            // 检查是否已存在管理员
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getRole, 1);
            if (count(queryWrapper) > 0) {
                throw new RuntimeException("管理员账号已存在，无法注册新的管理员账号");
            }
        } else {
            // 普通用户注册，设置角色为普通用户
            user.setRole(0);
        }

        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setStatus(1);
        user.setIsDeleted(0);

        // 保存用户
        save(user);
        return user;
    }

    @Override
    public User login(String username, String password) {
        User user = getByUsername(username);
        if (user == null || !passwordEncoder.matches(password, user.getPassword())) {
            throw new RuntimeException("用户名或密码错误");
        }
        if (user.getStatus() == 0) {
            throw new RuntimeException("账号已被禁用");
        }
        return user;
    }
    
    @Override
    public Result<User> login(User loginUser, HttpSession session) {
        try {
            if (loginUser == null || 
                !StringUtils.hasText(loginUser.getUsername()) || 
                !StringUtils.hasText(loginUser.getPassword())) {
                return Result.error("用户名和密码不能为空");
            }
            
            User user = getByUsername(loginUser.getUsername());
            if (user == null) {
                return Result.error("用户名不存在");
            }
            
            if (!passwordEncoder.matches(loginUser.getPassword(), user.getPassword())) {
                return Result.error("密码错误");
            }
            
            if (user.getStatus() == 0) {
                return Result.error("账号已被禁用");
            }
            
            // 更新登录信息
            user.setLastLoginTime(LocalDateTime.now());
            // 可以从HttpServletRequest中获取IP地址，这里简化处理
            user.setLastLoginIp("127.0.0.1");
            updateById(user);
            
            // 清除密码
            user.setPassword(null);
            
            // 保存用户信息到session
            session.setAttribute("user", user);
            
            return Result.success(user);
        } catch (Exception e) {
            log.error("用户登录出错", e);
            return Result.error("登录失败：" + e.getMessage());
        }
    }

    @Override
    public User getByUsername(String username) {
        return getOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, username)
                .eq(User::getIsDeleted, 0));
    }

    @Override
    @Transactional
    public void updateLoginInfo(Long userId, String ip) {
        User user = getById(userId);
        if (user != null) {
            user.setLastLoginTime(LocalDateTime.now());
            user.setLastLoginIp(ip);
            updateById(user);
        }
    }

    @Override
    @Transactional
    public void updateUserInfo(User user) {
        if (user != null && user.getId() != null) {
            // 保留原有的密码和登录信息
            User existingUser = getById(user.getId());
            if (existingUser != null) {
                user.setPassword(existingUser.getPassword());
                user.setLastLoginTime(existingUser.getLastLoginTime());
                user.setLastLoginIp(existingUser.getLastLoginIp());
                user.setStatus(existingUser.getStatus());
                user.setIsDeleted(existingUser.getIsDeleted());
                updateById(user);
            }
        }
    }
    
    @Override
    @Transactional
    public Result<User> updateProfile(User user, HttpSession session) {
        try {
            if (user == null || user.getId() == null) {
                return Result.error("用户信息不完整");
            }
            
            User existingUser = getById(user.getId());
            if (existingUser == null) {
                return Result.error("用户不存在");
            }
            
            // 只允许修改部分信息
            existingUser.setNickname(user.getNickname());
            existingUser.setPhone(user.getPhone());
            existingUser.setEmail(user.getEmail());
            existingUser.setAvatar(user.getAvatar());
            existingUser.setGender(user.getGender());
            
            // 更新用户信息
            updateById(existingUser);
            
            // 更新session中的用户信息
            existingUser.setPassword(null); // 清除密码
            session.setAttribute("user", existingUser);
            
            return Result.success(existingUser);
        } catch (Exception e) {
            log.error("更新用户信息出错", e);
            return Result.error("更新失败：" + e.getMessage());
        }
    }
    
    @Override
    @Transactional
    public Result<?> updatePassword(User user, HttpSession session) {
        try {
            if (user == null || user.getId() == null || 
                !StringUtils.hasText(user.getPassword()) || 
                !StringUtils.hasText(user.getOldPassword())) {
                return Result.error("参数不完整");
            }
            
            User existingUser = getById(user.getId());
            if (existingUser == null) {
                return Result.error("用户不存在");
            }
            
            // 验证旧密码
            if (!passwordEncoder.matches(user.getOldPassword(), existingUser.getPassword())) {
                return Result.error("旧密码错误");
            }
            
            // 更新密码
            existingUser.setPassword(passwordEncoder.encode(user.getPassword()));
            updateById(existingUser);
            
            // 清除session，要求重新登录
            session.invalidate();
            
            return Result.success();
        } catch (Exception e) {
            log.error("修改密码出错", e);
            return Result.error("修改失败：" + e.getMessage());
        }
    }
    
    @Override
    public Result<Page<User>> listAllUsers(int pageNum, int pageSize) {
        try {
            // 构建分页对象
            Page<User> page = new Page<>(pageNum, pageSize);
            
            // 构建查询条件
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getIsDeleted, 0);
            queryWrapper.orderByDesc(User::getCreateTime);
            
            // 执行分页查询
            page = page(page, queryWrapper);
            
            // 返回结果
            return Result.success(page);
        } catch (Exception e) {
            log.error("分页查询用户列表出错", e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }
    
    @Override
    public Result<Page<User>> searchUsers(String keyword, int pageNum, int pageSize) {
        try {
            // 构建分页对象
            Page<User> page = new Page<>(pageNum, pageSize);
            
            // 构建查询条件
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getIsDeleted, 0);
            
            // 添加搜索条件
            if (StringUtils.hasText(keyword)) {
                queryWrapper.and(wrapper -> 
                    wrapper.like(User::getUsername, keyword)
                           .or()
                           .like(User::getNickname, keyword)
                           .or()
                           .like(User::getPhone, keyword)
                           .or()
                           .like(User::getEmail, keyword)
                );
            }
            
            queryWrapper.orderByDesc(User::getCreateTime);
            
            // 执行分页查询
            page = page(page, queryWrapper);
            
            // 返回结果
            return Result.success(page);
        } catch (Exception e) {
            log.error("搜索用户列表出错", e);
            return Result.error("搜索失败：" + e.getMessage());
        }
    }
    
    @Override
    @Transactional
    public Result<Void> updateStatus(Long userId, Integer status) {
        try {
            if (userId == null || (status != 0 && status != 1)) {
                return Result.error("参数错误");
            }
            
            // 获取用户信息
            User user = getById(userId);
            if (user == null) {
                return Result.error("用户不存在");
            }
            
            // 不允许修改自己的状态
            if (user.getRole() == 1) {
                return Result.error("不能修改管理员状态");
            }
            
            // 更新状态
            LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(User::getId, userId);
            updateWrapper.set(User::getStatus, status);
            
            boolean result = update(updateWrapper);
            if (result) {
                return Result.success();
            } else {
                return Result.error("更新状态失败");
            }
        } catch (Exception e) {
            log.error("更新用户状态出错", e);
            return Result.error("操作失败：" + e.getMessage());
        }
    }
    
    @Override
    @Transactional
    public Result<Void> updateRole(Long userId, Integer role) {
        try {
            if (userId == null || (role != 0 && role != 1)) {
                return Result.error("参数错误");
            }
            
            // 获取用户信息
            User user = getById(userId);
            if (user == null) {
                return Result.error("用户不存在");
            }
            
            // 检查是否试图取消自己的管理员权限
            if (user.getRole() == 1 && role == 0) {
                // 检查是否还有其他管理员
                LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(User::getRole, 1)
                           .eq(User::getIsDeleted, 0)
                           .ne(User::getId, userId);
                long count = count(queryWrapper);
                if (count == 0) {
                    return Result.error("系统至少需要一个管理员");
                }
            }
            
            // 更新角色
            LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(User::getId, userId);
            updateWrapper.set(User::getRole, role);
            
            boolean result = update(updateWrapper);
            if (result) {
                return Result.success();
            } else {
                return Result.error("更新角色失败");
            }
        } catch (Exception e) {
            log.error("更新用户角色出错", e);
            return Result.error("操作失败：" + e.getMessage());
        }
    }
    
    @Override
    @Transactional
    public Result<Void> deleteUser(Long userId) {
        try {
            if (userId == null) {
                return Result.error("参数错误");
            }
            
            // 获取用户信息
            User user = getById(userId);
            if (user == null) {
                return Result.error("用户不存在");
            }
            
            // 不允许删除管理员
            if (user.getRole() == 1) {
                return Result.error("不能删除管理员账号");
            }
            
            // 逻辑删除
            LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(User::getId, userId);
            updateWrapper.set(User::getIsDeleted, 1);
            
            boolean result = update(updateWrapper);
            if (result) {
                return Result.success();
            } else {
                return Result.error("删除用户失败");
            }
        } catch (Exception e) {
            log.error("删除用户出错", e);
            return Result.error("操作失败：" + e.getMessage());
        }
    }
    
    @Override
    public Result<Integer[]> getUserStats() {
        try {
            // 统计总用户数
            long totalUsers = count(new LambdaQueryWrapper<User>()
                    .eq(User::getIsDeleted, 0));
            
            // 统计管理员数量
            long adminUsers = count(new LambdaQueryWrapper<User>()
                    .eq(User::getRole, 1)
                    .eq(User::getIsDeleted, 0));
            
            // 统计正常用户数
            long normalUsers = count(new LambdaQueryWrapper<User>()
                    .eq(User::getStatus, 1)
                    .eq(User::getIsDeleted, 0));
            
            // 统计禁用用户数
            long disabledUsers = count(new LambdaQueryWrapper<User>()
                    .eq(User::getStatus, 0)
                    .eq(User::getIsDeleted, 0));
            
            Integer[] stats = new Integer[]{
                    (int) totalUsers,
                    (int) adminUsers,
                    (int) normalUsers,
                    (int) disabledUsers
            };
            
            return Result.success(stats);
        } catch (Exception e) {
            log.error("获取用户统计数据出错", e);
            return Result.error("获取统计数据失败：" + e.getMessage());
        }
    }
    
    @Override
    @Transactional
    public Result<Void> resetPassword(Long userId) {
        try {
            if (userId == null) {
                return Result.error("参数错误");
            }
            
            // 获取用户信息
            User user = getById(userId);
            if (user == null) {
                return Result.error("用户不存在");
            }
            
            // 设置默认密码 123456
            String defaultPassword = "123456";
            // 加密密码
            String encryptedPassword = passwordEncoder.encode(defaultPassword);
            
            // 更新密码
            LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(User::getId, userId);
            updateWrapper.set(User::getPassword, encryptedPassword);
            
            boolean result = update(updateWrapper);
            if (result) {
                return Result.success();
            } else {
                return Result.error("重置密码失败");
            }
        } catch (Exception e) {
            log.error("重置用户密码出错", e);
            return Result.error("操作失败：" + e.getMessage());
        }
    }

    @Override
    public Map<String, Object> getUserGrowthData(String startDate, String endDate) {
        try {
            Map<String, Object> result = new HashMap<>();
            
            // 解析日期
            DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE;
            LocalDate start = LocalDate.parse(startDate, formatter);
            LocalDate end = LocalDate.parse(endDate, formatter);
            
            // 查询每天新增用户数量
            List<Map<String, Object>> dailyData = baseMapper.getUserGrowthByDay(startDate, endDate);
            
            // 总用户数
            Integer totalUsers = baseMapper.getTotalUserCount();
            
            // 新增用户数
            Integer newUsers = baseMapper.getNewUserCount(startDate, endDate);
            
            // 组装结果
            result.put("dailyData", dailyData);
            result.put("totalUsers", totalUsers);
            result.put("newUsers", newUsers);
            
            return result;
        } catch (Exception e) {
            log.error("获取用户增长数据出错", e);
            return new HashMap<>();
        }
    }
} 